<?php
class Cart_CodeprepayController extends Ext_Controller_Action
{
    private $_log;
    public function preDispatch()
    {
        parent::preDispatch();
        $writer = new Zend_Log_Writer_Stream(
            Zend_Registry::get('config')->prepay->log->transaction
        );
		$this->_helper->layout->setLayout( 'prepay' );
        $this->_log = new Zend_Log( $writer );
        $this->_log->info( "Prepay Method Selected" );
    }


    public function indexAction()
    {
		try{
            $client = new Zend_XmlRpc_Client(
                Zend_Registry::get('config')->api->cart->url
            );

            $userId = $this->_getParam('userId');
            $credential = $this->_getParam('credential');
            $amount = $this->_getParam('amount');
            $orderId = $this->_getParam('orderId');
            $urlSuccess = $this->_getParam('urlSuccess');
            $urlFail = $this->_getParam('urlFail');
            $sourceObjectName = $this->_getParam('sourceObjectName');
            $paymentMethodId = $this->_config->Payment->prepay->id;
            $user = new Ext_Model_User();

			$internalPrepaySession = new Zend_Session_Namespace('prepay');
			$this->view->msg = "";

			$invalidCode = $this->_getParam('invalidCode');
			if ( isset( $invalidCode ) )
			{
				if ( isset( $internalPrepaySession->userId ) ) {
					$this->view->msg = "C&oacute;digo $invalidCode inv&aacute;lido";
					$userId = $internalPrepaySession->userId;
		            $credential = $internalPrepaySession->credential;
		            $amount = $internalPrepaySession->amount;
		            $orderId = $internalPrepaySession->orderId;
		            $urlSuccess = $internalPrepaySession->urlSuccess;
		            $urlFail = $internalPrepaySession->urlFail;
		            $sourceObjectName = $internalPrepaySession->sourceObjectName;
				}
			} else {
				if( !isset( $amount ) )
				{
					if ( isset( $internalPrepaySession->userId ) ) {
    	                $this->view->msg = "C&oacute;digo $invalidCode inv&aacute;lido";
        	            $userId = $internalPrepaySession->userId;
           		        $credential = $internalPrepaySession->credential;
           	   			$amount = $internalPrepaySession->amount;
	                    $orderId = $internalPrepaySession->orderId;
	                    $urlSuccess = $internalPrepaySession->urlSuccess;
	                    $urlFail = $internalPrepaySession->urlFail;
    	                $sourceObjectName = $internalPrepaySession->sourceObjectName;
	                }
				}
			}

            if( !$user->checkCredential( $userId, $credential )){
                $this->_log->info("Credential is broken");
                throw new Ext_Exception ( 'Credential is broken');
            }

            $internalPrepaySession->amount = $amount;
            $internalPrepaySession->orderId = $orderId;
            $internalPrepaySession->userId = $userId;
            $internalPrepaySession->urlSuccess = $urlSuccess;
            $internalPrepaySession->urlFail = $urlFail;
            $internalPrepaySession->credential = $credential;
            $internalPrepaySession->sourceObjectName = $sourceObjectName;

            if( !$this->getRequest() ) {
                $this->_log->info("Error in Prepay Initilization. Exit");
                throw new Ext_Exception( 'Error in Prepay Initilization. Exit' );
            }

			$accountModel = new Cart_Model_Account();
			$validAccount = false;
            try{
	            $accountId = $accountModel->getAccountId( $userId, $credential, $userId, $sourceObjectName );
                $validAccount = true;
            } catch( Exception $error ) {
                $validAccount = false;
                $this->_log->info("Exception $error");
                throw new Ext_Exception ( 'Invalid Account');
            }

			if ( !$validAccount ) {
				$this->_redirect( $urlFail );
				exit(0);
			}

			$creditAccount = $accountModel->balanceAccount( $userId, $credential, $accountId );

            $this->view->creditAccount = $creditAccount;
			$this->view->totalAmount = $amount + $creditAccount;
			$this->view->urlFail = $urlFail;

			$this->view->prepayForm = new Cart_Form_PrePay();
            $this->view->prepayForm->setAction(
	                Zend_Registry::get('config')->prepay->url->load
	        );

        }catch( Exception $e ) {
            $this->_log->info("Exception");
            throw new Ext_Exception( $e );
        }
	}

	public function findcodeAction()
	{
		$this->_helper->layout->disableLayout();
		$code = $this->_getParam('CODE');
		$prepaidModel = new Cart_Model_CodePrepay();

		$internalPrepaySession = new Zend_Session_Namespace('prepay');
		$validCode = false;
		try{
			$statusCode = $prepaidModel->getStatus( $internalPrepaySession->userId, $internalPrepaySession->credential, $code );
			$validCode = true;
			if ( $statusCode['r_valid'] == 'A' )
			{
				$accountModel = new Cart_Model_Account();
				try{
	                $accountId = $accountModel->getAccountId( $internalPrepaySession->userId, $internalPrepaySession->credential,
															  $internalPrepaySession->userId, $internalPrepaySession->sourceObjectName );
	            } catch( Exception $error ) {
	                $this->_log->info("Exception $error");
	                throw new Ext_Exception ( 'Invalid Account');
	            }			  

				$sourceObjectId = 'POS_PREPAID_CODE';
                $sourceObjectCode = $statusCode['r_id'];

				// Insert Account Transaction
				$consumeCode = false;
				try{
					$consumeCode = $prepaidModel->consume( $internalPrepaySession->userId, $internalPrepaySession->credential, 
														   $code, $sourceObjectCode, $sourceObjectId );
				} catch( Exception $error ) {
					$this->_log->info("Codigo invalido status".$statusCode['r_valid'] );
	                $this->_redirect( 'Cart/codeprepay/index/invalidCode/'.$code );
		            exit(0);
				}

				if ( $consumeCode == true )
				{
					$valueRet =$accountModel->insertTransaction( $internalPrepaySession->userId, $internalPrepaySession->credential,
																 $accountId, $statusCode['r_value'], $sourceObjectCode, $sourceObjectId );
				} else {
					$this->_log->info("No se pudo consumir el codigo".$code );
	                $this->_redirect( 'Cart/codeprepay/index/invalidCode/'.$code );
	                exit(0);
				}

			} else {
				$this->_log->info("Codigo invalido status".$statusCode['r_valid'] );
      		    $this->_redirect( 'Cart/codeprepay/index/invalidCode/'.$code );
				exit(0);
			}

		} catch( Exception $error ) {
			$this->_log->info("No se puedo obtener la validacion del codigo");
			$validCode = false;
			$this->_redirect( 'Cart/codeprepay/index/invalidCode/'.$code );
			exit(0);
		}

		$this->_log->info("Codigo $code consumido correctamente");
		$urlSuccess = $internalPrepaySession->urlSuccess;
		$internalPrepaySession->setExpirationSeconds(1);

		$this->_redirect( $urlSuccess );
	}

}
